package Controller;

import Data.*;
import MyInterfaces.MassageType;
import Service.Main;
import Service.SendFile;
import Service.SendMassage;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.TextFlow;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.util.Callback;

import java.awt.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ChatWithStage {

    @FXML
    private ToggleButton CommonSentence;

    @FXML
    private VBox SentenceVbox;


    @FXML
    private ListView<String> Sentence;

    @FXML
    private Button DeleteSentence;

    @FXML
    private Button AddSentence;

    @FXML
    private FlowPane dynamicEmoji;

    @FXML
    private Tab nodynamic;

    @FXML
    private TextArea GetMassage;

    @FXML
    private ToggleButton file;

    @FXML
    private ToggleButton emoji;

    @FXML
    private ScrollPane dynamicScroll;

    @FXML
    private Tab dynamic;

    @FXML
    private ScrollPane SeeEmoji;

    @FXML
    private ToggleButton SendMassage;

    @FXML
    private FlowPane nodynamicEmoji;

    @FXML
    private ResourceBundle resources;

    @FXML
    private ListView<MassageData> MassageList;
    @FXML
    private URL location;

    private Socket socket;
    private String sender;
    private String receiver;
    private ObservableList<MassageData> oblist;

    public void setSocket(Socket socket) {
        this.socket = socket;
    }
    private ChatData mydata;

    public void setMydata(ChatData mydata) {
        this.mydata = mydata;
    }

    private boolean islooked=false;

    public void addMassage(MassageData massage)
    {
        System.out.println("此时数组大小为"+oblist.size());
        System.out.println(massage.getSender()+"给"+massage.getReceiver()+"发送的消息"+massage.getContent()+massage.getIs_file()+massage.getFile_name());
    //    oblist=MassageList.getItems();
    //    System.out.println(massage);
        oblist.add(massage);
        MassageList.refresh();
        System.out.println("此时数组大小为"+oblist.size());
        MassageList.scrollTo(oblist.size()-1);

    //    MassageList.setSelectionModel(null);
        MassageList.setCellFactory(new Callback<ListView<MassageData>, ListCell<MassageData>>() {
            @Override
            public ListCell<MassageData> call(ListView<MassageData> param) {
                ListCell<MassageData> list=new ListCell<MassageData>(){
                    @Override
                    protected void updateItem(MassageData arg0, boolean arg1) {
                        super.updateItem(arg0, arg1);
                        if(getIndex()==0)
                        {
                            //    setPrefHeight(50);
                            System.out.println("看看我执行了吗");
                            setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
                            HBox hBox=new HBox(30);
                            Button getmore=new Button("获得更多消息");
                            hBox.getChildren().add(getmore);
                            hBox.setAlignment(Pos.TOP_CENTER);
                            this.setGraphic(hBox);

                            getmore.setOnMouseClicked((MouseEvent event)->
                            {
                                //点击事件，是向服务器发送更多消息的请求
                                System.out.println(oblist.size()-1);
                                if(oblist.size()<=1)
                                {
                                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                    alert.setTitle("错误");
                                    alert.setHeaderText(null);
                                    alert.setContentText("没有更多消息了!");
                                    alert.showAndWait();
                                }
                                else
                                {
                                    event massage=new event();
                                    massage.setType(MassageType.Request_Chat_Massage);
                                    Timestamp timestamp=new Timestamp(System.currentTimeMillis());
                                    MassageData massageData=new MassageData(chatData.getSender_id(),chatData.getReceiver_id(),timestamp,"");
                                    massageData.setSum(oblist.size()-1);
                                    massage.setT(massageData);
                                    try {
                                        new SendMassage().sendMassage(massage);
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                            });
                        }
                        else if(arg1==false){
                            setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
                            HBox hbox=new HBox(30);
                            hbox.setAlignment(Pos.BASELINE_LEFT);//对齐显示

                            //需要头像，消息，以及日期
                            if(arg0.getSender().equals(chatData.getSender_id()))
                            {
                                //代表是自己发的
                                Image image=new Image(new ByteArrayInputStream(chatData.getSender_avatar()));
                                ImageView imageView=new ImageView(image);
                                imageView.setFitWidth(50);
                                imageView.setFitHeight(50);
                                Circle circle=new Circle(25,25,25);
                                imageView.setClip(circle);

                                Timestamp timestamp=arg0.getTimestamp();
                                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm");
                                String formatted=sdf.format(timestamp);
                                Label date=new Label(formatted);


                                TextFlow content=new TextFlow();
                                if(arg0.getIs_file()==1)
                                {
                                    //说明这是文件，显示一张图片，再显示文件路径
                                    Image fileimage=new Image("file:"+"E:\\JDK\\QQClient\\nox\\src\\img\\img_1.png");
                                    ImageView fileimageview=new ImageView(fileimage);
                                    fileimageview.setFitWidth(60);
                                    fileimageview.setFitHeight(60);

                                    Label filename=new Label(arg0.getFile_name());
                                    filename.setFont(new Font(10));
                                    VBox vBox=new VBox(10);
                                    vBox.setAlignment(Pos.TOP_RIGHT);
                                    vBox.getChildren().addAll(fileimageview,filename);

                                    HBox hBox=new HBox(20);
                                    hBox.getChildren().addAll(vBox,imageView);
                                    HBox.setHgrow(imageView,Priority.ALWAYS);
                                    HBox.setHgrow(vBox,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_RIGHT);

                                    VBox vBox1=new VBox();
                                    vBox1.setAlignment(Pos.TOP_CENTER);
                                    vBox1.getChildren().addAll(date,hBox);

                                    this.setGraphic(vBox1);
                                    prefHeightProperty().bind(hBox.prefHeightProperty());

                                    hBox.setOnMouseClicked((MouseEvent event)->
                                    {
                                        //先判断本地是否已经有这个文件
                                        File newfile=new File("F:\\qqclientfile"+"\\"+arg0.getFile_name());
                                        if(newfile.exists())
                                        {
                                            //打开这个文件
                                            Desktop desktop=Desktop.getDesktop();
                                            if(desktop.isSupported(Desktop.Action.OPEN))
                                            {
                                                try {
                                                    desktop.open(newfile);
                                                } catch (IOException e) {
                                                    throw new RuntimeException(e);
                                                }
                                            }
                                            else
                                            {
                                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                                alert.setTitle("错误");
                                                alert.setHeaderText(null);
                                                alert.setContentText("不支持打开此文件类型，请到"+newfile.getAbsolutePath()+"中查看!");
                                                alert.showAndWait();
                                            }
                                        }
                                        else
                                        {
                                            //没有就申请下载
                                            //向服务器发送请求，因为已经知道了该文件的id，发送一个请求id的代码

                                            event massage=new event();
                                            MassageData data=new MassageData();
//                                        data.setSender(arg0.getSender());
//                                        data.setReceiver(arg0.getReceiver());
                                            data.setFile_name(arg0.getFile_name());
                                            data.setFile_id(arg0.getFile_id());
                                            massage.setType(MassageType.Request_Get_File);
                                            massage.setT(data);
                                            try {
                                                new SendMassage().sendMassage(massage);
                                            } catch (IOException e) {
                                                throw new RuntimeException(e);
                                            }
                                        }

                                    });
                                }
                                else
                                {
                                    //说明这不是文件
                                    content=transfor(arg0.getContent());
                                    content.setMaxWidth(400);

                                    content.setTextAlignment(TextAlignment.RIGHT);
                                    content.setPadding(new Insets(20,20,20,20));
                                    BackgroundFill backgroundFill=new BackgroundFill(Color.LIGHTBLUE,CornerRadii.EMPTY,Insets.EMPTY);
                                    Background bg=new Background(backgroundFill);
                                    content.setBackground(bg);
                                    VBox vBox=new VBox(10);

                                    HBox hBox=new HBox(10);
                                    hBox.getChildren().addAll(content,imageView);

                                    HBox.setHgrow(imageView, Priority.ALWAYS);
                                    HBox.setHgrow(content,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_RIGHT);

                                    vBox.setAlignment(Pos.TOP_CENTER);
                                    vBox.getChildren().addAll(date,hBox);
                                    this.setGraphic(vBox);
                                    prefHeightProperty().bind(vBox.prefHeightProperty());
                                }
                                imageView.setOnMouseClicked((MouseEvent event)->{
                                    //加载自己的个人信息
                                    Stage stage=new Stage();
                                    File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\PrivateInformation.fxml");
                                    URL location= null;
                                    try {
                                        location = file.toURI().toURL();
                                    } catch (MalformedURLException e) {
                                        throw new RuntimeException(e);
                                    }
                                    FXMLLoader fxmlLoader=new FXMLLoader();
                                    fxmlLoader.setLocation(location);
                                    Parent root= null;
                                    try {
                                        root = fxmlLoader.load();
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                    stage.setTitle("个人信息修改");
                                    stage.setResizable(false);
                                    stage.setScene(new Scene(root,400,600));
                                    stage.show();
                                    PrivateInformation privateInformation=fxmlLoader.getController();
                                    Main.AllContronller.setPrivateInformationController(privateInformation);
                                    ChatMain chatMain= Main.getAllContronller().getChatMainController();
                                    privateInformation.setSocket(socket);
                                    PrivateInformationData mydata=chatMain.getMydata();
                                    privateInformation.changeInformation(mydata);

                                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                                        @Override
                                        public void handle(WindowEvent event) {
                                            stage.close();
                                            Main.AllContronller.setPrivateInformationController(null);
                                            //    System.out.print("监听到窗口关闭");
                                        }
                                    });
                                });
                            }
                            else
                            {
                                //这是对方发送的
                                Image image=new Image(new ByteArrayInputStream(chatData.getReceiver_avatar()));
                                ImageView imageView=new ImageView(image);
                                imageView.setFitWidth(50);
                                imageView.setFitHeight(50);
                                Circle circle=new Circle(25,25,25);
                                imageView.setClip(circle);

                                Timestamp timestamp=arg0.getTimestamp();
                                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm");
                                String formatted=sdf.format(timestamp);
                                Label date=new Label(formatted);

                                TextFlow content=new TextFlow();
                                if(arg0.getIs_file()==1)
                                {
                                    //说明这是文件
                                    //说明这是文件，显示一张图片，再显示文件路径
                                    Image fileimage=new Image("file:"+"E:\\JDK\\QQClient\\nox\\src\\img\\img_1.png");
                                    ImageView fileimageview=new ImageView(fileimage);
                                    fileimageview.setFitWidth(60);
                                    fileimageview.setFitHeight(60);

                                    Label filename=new Label(arg0.getFile_name());
                                    filename.setFont(new Font(10));
                                    VBox vBox=new VBox(10);
                                    vBox.setAlignment(Pos.TOP_LEFT);
                                    vBox.getChildren().addAll(date,fileimageview,filename);

                                    HBox hBox=new HBox(20);
                                    hBox.getChildren().addAll(imageView,vBox);
                                    HBox.setHgrow(imageView,Priority.ALWAYS);
                                    HBox.setHgrow(vBox,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_LEFT);

                                    VBox vBox1=new VBox();
                                    vBox1.setAlignment(Pos.TOP_CENTER);
                                    vBox1.getChildren().addAll(date,hBox);

                                    this.setGraphic(vBox1);
                                    prefHeightProperty().bind(hBox.prefHeightProperty());

                                    hBox.setOnMouseClicked((MouseEvent event)->
                                    {
                                        //先判断本地是否已经有这个文件
                                        File newfile=new File("F:\\qqclientfile"+"\\"+arg0.getFile_name());
                                        if(newfile.exists())
                                        {
                                            //打开这个文件
                                            Desktop desktop=Desktop.getDesktop();
                                            if(desktop.isSupported(Desktop.Action.OPEN))
                                            {
                                                try {
                                                    desktop.open(newfile);
                                                } catch (IOException e) {
                                                    throw new RuntimeException(e);
                                                }
                                            }
                                            else
                                            {
                                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                                alert.setTitle("错误");
                                                alert.setHeaderText(null);
                                                alert.setContentText("不支持打开此文件类型，请到"+newfile.getAbsolutePath()+"中查看!");
                                                alert.showAndWait();
                                            }
                                        }
                                        else
                                        {
                                            //没有就申请下载
                                            //向服务器发送请求，因为已经知道了该文件的id，发送一个请求id的代码

                                            event massage=new event();
                                            MassageData data=new MassageData();
//                                        data.setSender(arg0.getSender());
//                                        data.setReceiver(arg0.getReceiver());
                                            data.setFile_name(arg0.getFile_name());
                                            data.setFile_id(arg0.getFile_id());
                                            massage.setType(MassageType.Request_Get_File);
                                            massage.setT(data);
                                            try {
                                                new SendMassage().sendMassage(massage);
                                            } catch (IOException e) {
                                                throw new RuntimeException(e);
                                            }
                                        }

                                    });
                                    prefHeightProperty().bind(vBox.prefHeightProperty());
                                }
                                else
                                {
                                    content=transfor(arg0.getContent());
                                    content.setMaxWidth(400);

                                    content.setTextAlignment(TextAlignment.LEFT);
                                    content.setPadding(new Insets(20,20,20,20));
                                    BackgroundFill backgroundFill=new BackgroundFill(Color.LIGHTPINK,CornerRadii.EMPTY,Insets.EMPTY);
                                    Background bg=new Background(backgroundFill);
                                    content.setBackground(bg);

                                    VBox vBox=new VBox(10);

                                    HBox hBox=new HBox(10);
                                    hBox.getChildren().addAll(imageView,content);

                                    HBox.setHgrow(imageView, Priority.ALWAYS);
                                    HBox.setHgrow(content,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_LEFT);

                                    vBox.setAlignment(Pos.TOP_CENTER);
                                    vBox.getChildren().addAll(date,hBox);

                                    this.setGraphic(vBox);

                                    prefHeightProperty().bind(vBox.prefHeightProperty());
                                }

                                imageView.setOnMouseClicked((MouseEvent event)->
                                {
                                    Stage stage=new Stage();
                                    File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\PrivateInformation.fxml");
                                    URL location= null;
                                    try {
                                        location = file.toURI().toURL();
                                    } catch (MalformedURLException e) {
                                        throw new RuntimeException(e);
                                    }
                                    FXMLLoader fxmlLoader=new FXMLLoader();
                                    fxmlLoader.setLocation(location);
                                    Parent root= null;
                                    try {
                                        root = fxmlLoader.load();
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                    stage.setTitle("查看他人信息");
                                    stage.setResizable(false);
                                    stage.setScene(new Scene(root,400,600));
                                    stage.show();
                                    PrivateInformation privateInformation=fxmlLoader.getController();
                                    ChatMain chatMain= Main.getAllContronller().getChatMainController();
                                    PrivateInformationData Fdata=chatMain.getPID(arg0.getSender());
                                    privateInformation.setSocket(socket);
                                    System.out.println(arg0.getSender());
                                    privateInformation.lookFriend(Fdata);
                                });

                            }
                        }
                        else
                        {
//                            setPrefHeight(0);
                        }
                    }
                };
                return list;
            }
        });

    }


    public void setChatData(ChatData chatData) {
        this.chatData = chatData;
    }

    public ChatData chatData;

    public void setStage(ArrayList<MassageData> massagelist)
    {
        //清除之前的数据
        oblist=MassageList.getItems();
        oblist.clear();
        oblist=MassageList.getItems();
        oblist.addAll(massagelist);
        oblist.add(0,massagelist.get(0));

        System.out.println("此时的消息为"+oblist.size());

    //    MassageList.setSelectionModel(null);
        System.out.println("添加消息数组成功");

        MassageList.setCellFactory(new Callback<ListView<MassageData>, ListCell<MassageData>>() {
            @Override
            public ListCell<MassageData> call(ListView<MassageData> param) {
                ListCell<MassageData> list=new ListCell<MassageData>(){
                    @Override
                    protected void updateItem(MassageData arg0, boolean arg1) {
                        super.updateItem(arg0, arg1);
                        if(getIndex()==0)
                        {
                        //    setPrefHeight(50);
                            System.out.println("看看我执行了吗");
                            setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
                            HBox hBox=new HBox(30);
                            Button getmore=new Button("获得更多消息");
                            hBox.getChildren().add(getmore);
                            hBox.setAlignment(Pos.TOP_CENTER);
                            this.setGraphic(hBox);

                            getmore.setOnMouseClicked((MouseEvent event)->
                            {
                                //点击事件，是向服务器发送更多消息的请求
                                System.out.println(oblist.size()-1);
                                if(oblist.size()<=1)
                                {
                                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                    alert.setTitle("错误");
                                    alert.setHeaderText(null);
                                    alert.setContentText("没有更多消息了!");
                                    alert.showAndWait();
                                }
                                else
                                {
                                    event massage=new event();
                                    massage.setType(MassageType.Request_Chat_Massage);
                                    Timestamp timestamp=new Timestamp(System.currentTimeMillis());
                                    System.out.println(massagelist.get(1).getSender()+" "+massagelist.get(1).getReceiver());
                                    MassageData massageData=new MassageData(chatData.getSender_id(),chatData.getReceiver_id(),timestamp,"");
                                    massageData.setSum(oblist.size()-1);
                                    massage.setT(massageData);
                                    try {
                                        new SendMassage().sendMassage(massage);
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                            });
                        }
                        else if(arg1==false){
                            setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
                            HBox hbox=new HBox(30);
                            hbox.setAlignment(Pos.BASELINE_LEFT);//对齐显示

                            //需要头像，消息，以及日期
                            if(arg0.getSender().equals(chatData.getSender_id()))
                            {
                                //代表是自己发的
                                Image image=new Image(new ByteArrayInputStream(chatData.getSender_avatar()));
                                ImageView imageView=new ImageView(image);
                                imageView.setFitWidth(50);
                                imageView.setFitHeight(50);
                                Circle circle=new Circle(25,25,25);
                                imageView.setClip(circle);

                                Timestamp timestamp=arg0.getTimestamp();
                                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm");
                                String formatted=sdf.format(timestamp);
                                Label date=new Label(formatted);


                                TextFlow content=new TextFlow();
                                if(arg0.getIs_file()==1)
                                {
                                    //说明这是文件，显示一张图片，再显示文件路径
                                    Image fileimage=new Image("file:"+"E:\\JDK\\QQClient\\nox\\src\\img\\img_1.png");
                                    ImageView fileimageview=new ImageView(fileimage);
                                    fileimageview.setFitWidth(60);
                                    fileimageview.setFitHeight(60);

                                    Label filename=new Label(arg0.getFile_name());
                                    filename.setFont(new Font(10));
                                    VBox vBox=new VBox(10);
                                    vBox.setAlignment(Pos.TOP_RIGHT);
                                    vBox.getChildren().addAll(fileimageview,filename);

                                    HBox hBox=new HBox(20);
                                    hBox.getChildren().addAll(vBox,imageView);
                                    HBox.setHgrow(imageView,Priority.ALWAYS);
                                    HBox.setHgrow(vBox,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_RIGHT);

                                    VBox vBox1=new VBox();
                                    vBox1.setAlignment(Pos.TOP_CENTER);
                                    vBox1.getChildren().addAll(date,hBox);

                                    this.setGraphic(vBox1);
                                    prefHeightProperty().bind(hBox.prefHeightProperty());

                                    hBox.setOnMouseClicked((MouseEvent event)->
                                    {
                                        //先判断本地是否已经有这个文件
                                        File newfile=new File("F:\\qqclientfile"+"\\"+arg0.getFile_name());
                                        if(newfile.exists())
                                        {
                                            //打开这个文件
                                            Desktop desktop=Desktop.getDesktop();
                                            if(desktop.isSupported(Desktop.Action.OPEN))
                                            {
                                                try {
                                                    desktop.open(newfile);
                                                } catch (IOException e) {
                                                    throw new RuntimeException(e);
                                                }
                                            }
                                            else
                                            {
                                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                                alert.setTitle("错误");
                                                alert.setHeaderText(null);
                                                alert.setContentText("不支持打开此文件类型，请到"+newfile.getAbsolutePath()+"中查看!");
                                                alert.showAndWait();
                                            }
                                        }
                                        else
                                        {
                                            //没有就申请下载
                                            //向服务器发送请求，因为已经知道了该文件的id，发送一个请求id的代码

                                            event massage=new event();
                                            MassageData data=new MassageData();
//                                        data.setSender(arg0.getSender());
//                                        data.setReceiver(arg0.getReceiver());
                                            data.setFile_name(arg0.getFile_name());
                                            data.setFile_id(arg0.getFile_id());
                                            massage.setType(MassageType.Request_Get_File);
                                            massage.setT(data);
                                            try {
                                                new SendMassage().sendMassage(massage);
                                            } catch (IOException e) {
                                                throw new RuntimeException(e);
                                            }
                                        }

                                    });
                                }
                                else
                                {
                                    //说明这不是文件
                                    content=transfor(arg0.getContent());
                                    content.setMaxWidth(400);

                                    content.setTextAlignment(TextAlignment.RIGHT);
                                    content.setPadding(new Insets(20,20,20,20));
                                    BackgroundFill backgroundFill=new BackgroundFill(Color.LIGHTBLUE,CornerRadii.EMPTY,Insets.EMPTY);
                                    Background bg=new Background(backgroundFill);
                                    content.setBackground(bg);
                                    VBox vBox=new VBox(10);

                                    HBox hBox=new HBox(10);
                                    hBox.getChildren().addAll(content,imageView);

                                    HBox.setHgrow(imageView, Priority.ALWAYS);
                                    HBox.setHgrow(content,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_RIGHT);

                                    vBox.setAlignment(Pos.TOP_CENTER);
                                    vBox.getChildren().addAll(date,hBox);
                                    this.setGraphic(vBox);
                                    prefHeightProperty().bind(vBox.prefHeightProperty());
                                }
                                imageView.setOnMouseClicked((MouseEvent event)->{
                                    //加载自己的个人信息
                                    Stage stage=new Stage();
                                    File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\PrivateInformation.fxml");
                                    URL location= null;
                                    try {
                                        location = file.toURI().toURL();
                                    } catch (MalformedURLException e) {
                                        throw new RuntimeException(e);
                                    }
                                    FXMLLoader fxmlLoader=new FXMLLoader();
                                    fxmlLoader.setLocation(location);
                                    Parent root= null;
                                    try {
                                        root = fxmlLoader.load();
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                    stage.setTitle("个人信息修改");
                                    stage.setResizable(false);
                                    stage.setScene(new Scene(root,400,600));
                                    stage.show();
                                    PrivateInformation privateInformation=fxmlLoader.getController();
                                    Main.AllContronller.setPrivateInformationController(privateInformation);
                                    ChatMain chatMain= Main.getAllContronller().getChatMainController();
                                    privateInformation.setSocket(socket);
                                    PrivateInformationData mydata=chatMain.getMydata();
                                    privateInformation.changeInformation(mydata);

                                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                                        @Override
                                        public void handle(WindowEvent event) {
                                            stage.close();
                                            Main.AllContronller.setPrivateInformationController(null);
                                            //    System.out.print("监听到窗口关闭");
                                        }
                                    });
                                });
                            }
                            else
                            {
                                //这是对方发送的
                                Image image=new Image(new ByteArrayInputStream(chatData.getReceiver_avatar()));
                                ImageView imageView=new ImageView(image);
                                imageView.setFitWidth(50);
                                imageView.setFitHeight(50);
                                Circle circle=new Circle(25,25,25);
                                imageView.setClip(circle);

                                Timestamp timestamp=arg0.getTimestamp();
                                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm");
                                String formatted=sdf.format(timestamp);
                                Label date=new Label(formatted);

                                TextFlow content=new TextFlow();
                                if(arg0.getIs_file()==1)
                                {
                                    //说明这是文件
                                    //说明这是文件，显示一张图片，再显示文件路径
                                    Image fileimage=new Image("file:"+"E:\\JDK\\QQClient\\nox\\src\\img\\img_1.png");
                                    ImageView fileimageview=new ImageView(fileimage);
                                    fileimageview.setFitWidth(60);
                                    fileimageview.setFitHeight(60);

                                    Label filename=new Label(arg0.getFile_name());
                                    filename.setFont(new Font(10));
                                    VBox vBox=new VBox(10);
                                    vBox.setAlignment(Pos.TOP_LEFT);
                                    vBox.getChildren().addAll(date,fileimageview,filename);

                                    HBox hBox=new HBox(20);
                                    hBox.getChildren().addAll(imageView,vBox);
                                    HBox.setHgrow(imageView,Priority.ALWAYS);
                                    HBox.setHgrow(vBox,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_LEFT);

                                    VBox vBox1=new VBox();
                                    vBox1.setAlignment(Pos.TOP_CENTER);
                                    vBox1.getChildren().addAll(date,hBox);

                                    this.setGraphic(vBox1);
                                    prefHeightProperty().bind(hBox.prefHeightProperty());

                                    hBox.setOnMouseClicked((MouseEvent event)->
                                    {
                                        //先判断本地是否已经有这个文件
                                        File newfile=new File("F:\\qqclientfile"+"\\"+arg0.getFile_name());
                                        if(newfile.exists())
                                        {
                                            //打开这个文件
                                            Desktop desktop=Desktop.getDesktop();
                                            if(desktop.isSupported(Desktop.Action.OPEN))
                                            {
                                                try {
                                                    desktop.open(newfile);
                                                } catch (IOException e) {
                                                    throw new RuntimeException(e);
                                                }
                                            }
                                            else
                                            {
                                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                                alert.setTitle("错误");
                                                alert.setHeaderText(null);
                                                alert.setContentText("不支持打开此文件类型，请到"+newfile.getAbsolutePath()+"中查看!");
                                                alert.showAndWait();
                                            }
                                        }
                                        else
                                        {
                                            //没有就申请下载
                                            //向服务器发送请求，因为已经知道了该文件的id，发送一个请求id的代码

                                            event massage=new event();
                                            MassageData data=new MassageData();
//                                        data.setSender(arg0.getSender());
//                                        data.setReceiver(arg0.getReceiver());
                                            data.setFile_name(arg0.getFile_name());
                                            data.setFile_id(arg0.getFile_id());
                                            massage.setType(MassageType.Request_Get_File);
                                            massage.setT(data);
                                            try {
                                                new SendMassage().sendMassage(massage);
                                            } catch (IOException e) {
                                                throw new RuntimeException(e);
                                            }
                                        }

                                    });
                                    prefHeightProperty().bind(vBox.prefHeightProperty());
                                }
                                else
                                {
                                    content=transfor(arg0.getContent());
                                    content.setMaxWidth(400);

                                    content.setTextAlignment(TextAlignment.LEFT);
                                    content.setPadding(new Insets(20,20,20,20));
                                    BackgroundFill backgroundFill=new BackgroundFill(Color.LIGHTPINK,CornerRadii.EMPTY,Insets.EMPTY);
                                    Background bg=new Background(backgroundFill);
                                    content.setBackground(bg);

                                    VBox vBox=new VBox(10);

                                    HBox hBox=new HBox(10);
                                    hBox.getChildren().addAll(imageView,content);

                                    HBox.setHgrow(imageView, Priority.ALWAYS);
                                    HBox.setHgrow(content,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_LEFT);

                                    vBox.setAlignment(Pos.TOP_CENTER);
                                    vBox.getChildren().addAll(date,hBox);

                                    this.setGraphic(vBox);

                                    prefHeightProperty().bind(vBox.prefHeightProperty());
                                }

                                imageView.setOnMouseClicked((MouseEvent event)->
                                {
                                    Stage stage=new Stage();
                                    File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\PrivateInformation.fxml");
                                    URL location= null;
                                    try {
                                        location = file.toURI().toURL();
                                    } catch (MalformedURLException e) {
                                        throw new RuntimeException(e);
                                    }
                                    FXMLLoader fxmlLoader=new FXMLLoader();
                                    fxmlLoader.setLocation(location);
                                    Parent root= null;
                                    try {
                                        root = fxmlLoader.load();
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                    stage.setTitle("查看他人信息");
                                    stage.setResizable(false);
                                    stage.setScene(new Scene(root,400,600));
                                    stage.show();
                                    PrivateInformation privateInformation=fxmlLoader.getController();
                                    ChatMain chatMain= Main.getAllContronller().getChatMainController();
                                    PrivateInformationData Fdata=chatMain.getPID(arg0.getSender());
                                    privateInformation.setSocket(socket);
                                    System.out.println(arg0.getSender());
                                    privateInformation.lookFriend(Fdata);
                                });

                            }
                        }
                        else
                        {
//                            setPrefHeight(0);
                        }
                    }
                };
                return list;
            }
        });

        System.out.println("在显示了");
        MassageList.scrollTo(oblist.size()-1);
    }
    private static final String regex="\\[\\{(1[0-8][0-7]|[1-9][0-9]|[1-9])(dynamic|static)}]";
    private static final Pattern PATTERN=Pattern.compile(regex);
    public TextFlow transfor(String massage)
    {

        TextFlow content=new TextFlow();
        content.setPadding(new Insets(10));
        Matcher matcher= PATTERN.matcher(massage);
        String res=new String();
        int index=0;
        while(matcher.find())
        {
            String match=matcher.group();
            if(matcher.start()>index)
            {
                Text text=new Text(massage.substring(index,matcher.start()));
            //    text.setFont(new Font("Arial",30));
                content.getChildren().add(text);
            }

            Image image=null;
            ImageView imageView=new ImageView();
            System.out.println(match.substring(0,match.length()));
            if(match.substring(0,match.length()).contains("dynamic"))
            {
                image=new Image("file:"+"E:\\JDK\\QQClient\\nox\\src\\emoji\\dynamic\\"+match.substring(2,match.length()-9)+".gif");
                imageView.setImage(image);
            }
            else if(match.substring(0,match.length()).contains("static"))
            {
                image=new Image("file:"+"E:\\JDK\\QQClient\\nox\\src\\emoji\\static\\"+match.substring(2,match.length()-8)+".png");
                imageView.setImage(image);
            }
            imageView.setFitWidth(20);
            imageView.setPreserveRatio(true);
            imageView.setFitHeight(20);
            content.getChildren().add(imageView);
            index=matcher.end();
        }
        if(index<massage.length())
        {
            Text text=new Text(massage.substring(index));
            content.getChildren().add(text);
        }

        return content;
    }


    @FXML
    void SendMassageAction(ActionEvent event) throws IOException {
        if(GetMassage.getText().equals(""))
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("错误");
            alert.setHeaderText(null);
            alert.setContentText("消息为空!");
            alert.showAndWait();
        }
        else
        {
            event massage=new event();
            massage.setType(MassageType.Send_Massage_To_One);
            Timestamp timestamp=new Timestamp(System.currentTimeMillis());

            MassageData newmassage=new MassageData(chatData.getSender_id(),chatData.getReceiver_id(),timestamp,GetMassage.getText());
            massage.setT(newmassage);

            new SendMassage().sendMassage(massage);
            GetMassage.clear();
        }
    }

    @FXML
    void initialize() {
        assert GetMassage != null : "fx:id=\"GetMassage\" was not injected: check your FXML file 'Controller.ChatWithStage.fxml'.";
        assert SendMassage != null : "fx:id=\"SendMassage\" was not injected: check your FXML file 'Controller.ChatWithStage.fxml'.";
        GetMassage.setPrefRowCount(5);
        GetMassage.setPrefRowCount(50);
        GetMassage.setWrapText(true);

        oblist=MassageList.getItems();
        oblist.clear();
        oblist=MassageList.getItems();
        //设置横向滚动条不可以用
        SeeEmoji.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);

        SeeEmoji.setVisible(false);
        SeeEmoji.setDisable(true);
        for (int i = 0; i < 188; i++) {
            String path="E:\\JDK\\QQClient\\nox\\src\\emoji\\dynamic\\"+(i+1)+".gif";
            Image image=new Image("file:"+path);
            ImageView imageView=new ImageView();
            imageView.setImage(image);
            imageView.setPreserveRatio(true);
            imageView.setFitWidth(20);
            imageView.setFitWidth(20);
            dynamicEmoji.getChildren().add(imageView);
            String finalPath = path;
            int finalI2 = i;
            imageView.setOnMouseClicked((MouseEvent event)->
            {
                int position=GetMassage.getCaretPosition();
                GetMassage.replaceText(position,position,"[{"+(finalI2 +1)+"dynamic"+"}]");
                System.out.println(finalPath);
            });

            path="E:\\JDK\\QQClient\\nox\\src\\emoji\\static\\"+(i+1)+".png";
            image=new Image("file:"+path);
            imageView=new ImageView();
            imageView.setImage(image);
            imageView.setPreserveRatio(true);
            imageView.setFitWidth(20);
            imageView.setFitWidth(20);
            nodynamicEmoji.getChildren().add(imageView);

            String finalPath1 = path;
            int finalI1 = i;
            imageView.setOnMouseClicked((MouseEvent event)->
            {
                int position=GetMassage.getCaretPosition();
                GetMassage.replaceText(position,position,"[{"+(finalI1 +1)+"static"+"}]");
                System.out.println(finalPath1);
            });
        }

        SentenceVbox.setVisible(false);
        SentenceVbox.setDisable(true);
        isSentenceVox=false;
    }

    boolean isSentenceVox;

    private boolean isemoji=false;
    public void SendEmoji(ActionEvent actionEvent)
    {
        if(isemoji)
        {
            isemoji=false;
            SeeEmoji.setVisible(false);
            SeeEmoji.setDisable(true);
        }
        else
        {
            isemoji=true;
            SeeEmoji.setDisable(false);
            SeeEmoji.setVisible(true);
        }
    }
    public void ResultSendFile(event returnmassge)
    {
        if(returnmassge.getType().equals(MassageType.Send_File_Success))
        {

            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("成功");
            alert.setHeaderText(null);
            alert.setContentText("发送给"+chatData.getReceiver_id()+"的文件成功");
            alert.showAndWait();

            MassageData massageData=(MassageData) returnmassge.getT();
            addMassage(massageData);

            Platform.runLater(() -> {
            ChatMain chatMain=Main.AllContronller.getChatMainController();
            chatMain.getMsgList().addOneMsg(massageData.getReceiver(),massageData);
            });
        }
        else if(returnmassge.getType().equals(MassageType.Send_File_Fail))
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("失败");
            alert.setHeaderText(null);
            alert.setContentText("发送给"+chatData.getReceiver_id()+"的文件失败");
            alert.showAndWait();
        }
    }
    public void SendFile(ActionEvent actionEvent) throws IOException, NoSuchAlgorithmException {
        Stage stage=new Stage();
        File file;
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择文件");

        fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))
        );

        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("All ", "*.*")
        );
        file= fileChooser.showOpenDialog(stage);

        if(file!=null) {
            //已经读取好了
            //先发送一个我需要上传文件的消息
            event massage=new event();
            massage.setType(MassageType.Send_File);
            MassageData data=new MassageData();
            SendFile sendFile=new SendFile(file.getAbsolutePath());
            data=sendFile.sendToFile();
            data.setSender(chatData.getSender_id());
            data.setReceiver(chatData.getReceiver_id());
            data.setTimestamp(new Timestamp(System.currentTimeMillis()));
            data.setMD5(getMD5(file));
            data.setFile_name(file.getName());
            data.setIs_file(1);

            String suffixname=null;

            if(file!=null)
            {
                suffixname=file.getName();
                int dotIndex=suffixname.lastIndexOf('.');
                if(dotIndex>0&&dotIndex<suffixname.length()-1)
                {
                    data.setSuffix_name(suffixname.substring(dotIndex+1));
                    System.out.println(suffixname.substring(dotIndex+1));
                }
                else data.setSuffix_name("");
            }
            System.out.println("后缀名称为"+data.getSuffix_name());

            massage.setT(data);
            new SendMassage().sendMassage(massage);

        }

    }

    public void CloseStage()
    {
        Platform.runLater(() -> {
            Stage stage = (Stage) GetMassage.getScene().getWindow();
            if (stage != null) {
                stage.close();
            }
        });
    }
        public static String getMD5(File file) throws IOException, NoSuchAlgorithmException
        {
            InputStream inputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            int numRead = 0;
            while ((numRead = inputStream.read(buffer)) > 0) {
                md5.update(buffer, 0, numRead);
            }
            inputStream.close();
            byte[] md5Bytes = md5.digest();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < md5Bytes.length; i++) {
                if (Integer.toHexString(0xFF & md5Bytes[i]).length() == 1) {
                    sb.append("0").append(Integer.toHexString(0xFF & md5Bytes[i]));
                } else {
                    sb.append(Integer.toHexString(0xFF & md5Bytes[i]));
                }
            }
            return sb.toString();
        }

    ObservableList<String> sentenceoblist;

        public void setCommonSentence(ArrayList<String> arrayList)
        {
            sentenceoblist= FXCollections.observableArrayList();
            Sentence.setItems(sentenceoblist);

            sentenceoblist.setAll(arrayList);
            Sentence.refresh();

            System.out.println(arrayList.size()+"  "+sentenceoblist.size());

            Sentence.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
                @Override
                public ListCell<String> call(ListView<String> param) {
                    ListCell<String> list=new ListCell<String>(){
                        @Override
                        protected void updateItem(String arg0, boolean arg1) {
                            super.updateItem(arg0, arg1);
                            if(!arg1)
                            {
                                setPrefHeight(30);
                            //    setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
                                HBox hBox=new HBox(10);
                                Label label=new Label(arg0);
                                label.setFont(new Font(15));
                                hBox.setAlignment(Pos.BASELINE_LEFT);

                                hBox.getChildren().add(label);
                                this.setGraphic(hBox);

                            }
                            else
                            {
                                setPrefHeight(0);
                                return;
                            }
                        }
                    };
                    return list;
                }
            });

            Sentence.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
                //s：改变前的值    t1：改变后的值
                @Override
                public void changed(ObservableValue<? extends String> observableValue, String s, String t1) {
                    //    UserInfolist.getSelectionModel().clearSelection();
                    if(t1!=null)
                    {
                        current_sentence=t1;
                        //添加到消息框当中
                         int position=GetMassage.getCaretPosition();
                         GetMassage.replaceText(position,position,t1);
                         System.out.println(t1);

                    }
                    else return;
                }
            });

        }

        public String current_sentence=null;

    public void CommonSentenceAction(ActionEvent actionEvent) {
        if(!isSentenceVox)
        {
            SentenceVbox.setVisible(true);
            SentenceVbox.setDisable(false);
            isSentenceVox=true;
        }
        else
        {
            SentenceVbox.setVisible(false);
            SentenceVbox.setDisable(true);
            isSentenceVox=false;
        }
    }

    public void AddSentenceAction(ActionEvent actionEvent) throws IOException {
        if(sentenceoblist.size()>=20)
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("错误");
            alert.setHeaderText(null);
            alert.setContentText("最多只能有20条数据!");
            alert.showAndWait();
            return;
        }
        else
        {
            TextInputDialog dialog = new TextInputDialog("你好");
            dialog.setTitle("请输入你想要的常用语");
            dialog.setHeaderText("键入常用语");
            dialog.setContentText("请输入:");

            String newsentence="";
            Optional<String> result = dialog.showAndWait();
            if (result.isPresent()){
                newsentence=result.get();
                System.out.println("Your name: " + result.get());
            }

            //向服务器发送需要添加常用语的消息
            if(newsentence=="") return ;
            CommonSentenceData sentenceData=new CommonSentenceData(chatData.getSender_id(),newsentence);

            event massage=new event();
            massage.setType(MassageType.Add_Common_Sentence);
            massage.setT(sentenceData);

            new SendMassage().sendMassage(massage);

        }
    }

    public void DeleteSentenceAction(ActionEvent actionEvent) throws IOException {
        if(sentenceoblist.size()<=0)
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("错误");
            alert.setHeaderText(null);
            alert.setContentText("已经没有常用语，不可以乱点!");
            alert.showAndWait();
            return;
        }
        else
        {
            if(current_sentence!=null)
            {
                CommonSentenceData sentenceData=new CommonSentenceData(chatData.getSender_id(),current_sentence);

                event massage=new event();
                massage.setType(MassageType.Delete_Common_Sentence);
                massage.setT(sentenceData);

                new SendMassage().sendMassage(massage);
            }
            else
            {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("错误");
                alert.setHeaderText(null);
                alert.setContentText("您还没有选择!");
                alert.showAndWait();
            }
            //向服务器发送一条需要删除常用语的操作
        }
    }
}
